package com.java1412.controller;

import com.java1412.entity.Book;
import com.java1412.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * @author java1412
 * @create 2021-07-21 12:25
 */
@Slf4j
@RestController
@RequestMapping("/book")
public class ElasticController {
    @Autowired
    private BookService bookService;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 创建索引
     */
    @PostMapping("/create")
    public void createIndex() {
        elasticsearchTemplate.createIndex(Book.class);
    }

    @PostMapping("/save")
    public void save() {
        Book book = new Book("100", "ElasticSearch第2中实现方式", "java1412", "2021-07-21");
        log.warn(book.toString());
        bookService.save(book);
    }

    @GetMapping("/id/{id}")
    public Book getBookById(@PathVariable("id") String id) {
        Optional<Book> opt = bookService.findById(id);
        Book book = opt.get();
        log.warn(book.toString());
        return book;
    }
}
